/**
 * 统一响应格式拦截器
 */

import {
  Injectable,
  NestInterceptor,
  ExecutionContext,
  CallHandler,
} from '@nestjs/common';
import { Observable } from 'rxjs';
import { map } from 'rxjs/operators';
import { RETURN_MESSAGE } from '../decorator/return-message.decorator';
import { Reflector } from '@nestjs/core';
import { CODE } from '../enum/code.enum';

export interface Response<T> {
  data: T;
}

function option(params: string | object, dMessage: string) {
  let message = dMessage || '操作成功';
  let code = CODE.SUCCESS;
  let data = params;
  if (typeof data === 'object') {
    if ('code' in data && typeof data.code === 'number') {
      code = data.code;
      delete data.code;
    }
    if ('message' in data && typeof data.message === 'string') {
      message = data.message;
      delete data.message;
    }
    if ('data' in data) {
      data = data.data as string | object;
    }
  }
  return {
    code: code,
    data: data,
    message,
  };
}

@Injectable()
export class TransformInterceptor<T>
  implements NestInterceptor<T, Response<T>>
{
  constructor(private readonly reflector: Reflector) {}

  intercept(
    context: ExecutionContext,
    next: CallHandler,
  ): Observable<Response<T>> {
    const dMessage = this.reflector.get<string>(
      RETURN_MESSAGE,
      context.getHandler(),
    );

    return next.handle().pipe(map((data) => <any>option(data, dMessage)));
  }
}
